import { ProTable, type ProColumns } from '@/components/Pro';
import { statisticWorkStatusControllerGetMonthYearWorkStatusPage } from '@/services/ess/statisticWorkstatus';
import { deviceTreeData } from '@/utils/formatterTree';
import { useIntl } from '@umijs/max';
import dayjs from 'dayjs';
import _ from 'lodash';
import moment from 'moment';
import React, { ReactNode, useRef, useState } from 'react';
import './Common.less';

type IProps = {
  treeData: deviceTreeData[];
  changeReportData: (data: any) => void;
};
const MonthReport: React.FC<IProps> = (props) => {
  const intl = useIntl();
  const tableRef = useRef(null);
  const { treeData, changeReportData } = props;
  //分区维度
  const [cascaderVal, setCascaderVal] = useState(treeData[0].uniqueId);
  const [code, setCode] = useState(treeData[0].stationId);
  const [areaIdList, setAreaIdList] = useState(null);

  const [total, setTotal] = useState({
    chargeCount: '',
    dischargeCount: '',
    standbyCount: '',
    debugCount: '',
    faultCount: '',
    chargeTime: '',
    dischargeTime: '',
    standbyTime: '',
    debugTime: '',
    faultTime: '',
    dischargeEnergy: '',
    chargeEnergy: '',
    pocOnGridEnergy: '',
    pocOffGridEnergy: '',
  });
  const [isEmpty, changeIsEmpty] = useState(false);
  const [workDate, setWorkDate] = useState(dayjs);
  const [stationToken, changeStationToken] = useState(true);
  const [dataType, setDataType] = useState('1');

  const columns: ProColumns[] = [
    {
      valueType: 'index',
      title: intl.formatMessage({ id: 'batteryVoltage.tableNo' }),
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'statistics.common.period' }),
      dataIndex: 'date',
      hideInSearch: true,
      width: 120,
    },
    {
      title: intl.formatMessage({ id: 'statistics.income.select' }),
      hideInTable: true,
      dataIndex: 'date',
      valueType: 'date',
      fieldProps: {
        allowClear: false,
        value: workDate,
        picker: 'month',
        format: 'YYYY-MM',
        disabledDate: (current) => {
          return current && current > moment().endOf('month');
        },
        onChange: (e: ReactNode, dateString: string) => {
          setWorkDate(e);
          changeReportData({
            dateType: 'month',
            dataType: dataType,
            code: code,
            date: dateString,
            areaIdList: areaIdList,
          });
        },
      },
      initialValue: dayjs(),
    },
    // 分区维度
    {
      title: intl.formatMessage({ id: 'statistics.work.dimensions' }),
      dataIndex: 'areaIdList',
      hideInTable: true,
      valueType: 'cascader',
      fieldProps: {
        changeOnSelect: true,
        allowClear: false,
        value: cascaderVal,
        options: treeData,
        fieldNames: {
          label: 'deviceName',
          value: 'uniqueId',
          children: 'subDevices',
        },
        onChange: (e: string[], params: API.DeviceTreeVO[]) => {
          setCascaderVal(e);
          const selectedItem = _.last(params);
          // 分区维度
          setDataType(
            selectedItem?.nodeType === 'ROOT' ? '1' : selectedItem?.nodeType === 'AREA' ? '3' : '2',
          );
          setCode(
            selectedItem?.nodeType === 'ROOT' ? selectedItem?.stationId : selectedItem?.deviceCode,
          );
          setAreaIdList(selectedItem?.nodeType === 'AREA' ? selectedItem?.areaId : null);
          changeReportData({
            dateType: 'month',
            date: dayjs(workDate).format('YYYY-MM'),
            dataType:
              selectedItem?.nodeType === 'ROOT'
                ? '1'
                : selectedItem?.nodeType === 'AREA'
                ? '3'
                : '2',
            code:
              selectedItem?.nodeType === 'ROOT'
                ? selectedItem?.stationId
                : selectedItem?.deviceCode,
            areaIdList: selectedItem?.nodeType === 'AREA' ? selectedItem?.areaId : null,
          });
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'statistics.work.chargeTimes' }),
      dataIndex: 'chargeCount',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.work.dischargeTimes' }),
      dataIndex: 'dischargeCount',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.work.standbyTimes' }),
      dataIndex: 'standbyCount',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.work.debugTimes' }),
      dataIndex: 'debugCount',
      hideInSearch: true,
      hideInTable: !stationToken,
    },
    {
      title: intl.formatMessage({ id: 'statistics.work.faultTimes' }),
      dataIndex: 'faultCount',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.work.chargeTime' })}(${intl.formatMessage({
        id: 'statistics.common.mins',
      })})`,
      dataIndex: 'chargeTime',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.work.dischargeTime' })}(${intl.formatMessage({
        id: 'statistics.common.mins',
      })})`,
      dataIndex: 'dischargeTime',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.work.standbyTime' })}(${intl.formatMessage({
        id: 'statistics.common.mins',
      })})`,
      dataIndex: 'standbyTime',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.work.debugTime' })}(${intl.formatMessage({
        id: 'statistics.common.mins',
      })})`,
      dataIndex: 'debugTime',
      hideInSearch: true,
      hideInTable: !stationToken,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.work.faultTime' })}(${intl.formatMessage({
        id: 'statistics.common.mins',
      })})`,
      dataIndex: 'faultTime',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.common.discharge' })}(kWh)`,
      dataIndex: 'dischargeEnergy',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.common.charge' })}(kWh)`,
      dataIndex: 'chargeEnergy',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'batteryVoltage.safe.onGrid' })}(kWh)`,
      dataIndex: 'pocOnGridEnergy',
      hideInSearch: true,
      width: 120,
    },
    {
      title: `${intl.formatMessage({ id: 'batteryVoltage.safe.offGrid' })}(kWh)`,
      dataIndex: 'pocOffGridEnergy',
      hideInSearch: true,
      width: 120,
    },
  ];
  return (
    <>
      <ProTable
        headerTitle=" "
        style={{ position: 'relative', zIndex: '10' }}
        actionRef={tableRef}
        columns={columns}
        onReset={() => {
          setWorkDate(dayjs());
          setDataType('1');
          changeReportData({
            dateType: 'month',
            date: dayjs().format('YYYY-MM'),
            dataType: '1',
            code: treeData[0].stationId,
            areaIdList: null,
          });
          setAreaIdList(null);
          setCode(treeData[0].stationId);
          setCascaderVal(treeData[0].uniqueId);
          tableRef?.current?.reset();
        }}
        request={async (values) => {
          changeStationToken(dataType === '1');
          const params = {
            dataType: dataType,
            current: values?.current,
            pageSize: values?.pageSize,
            dateType: 'month',
            date: dayjs(workDate).format('YYYY-MM'),
            code: dataType !== '3' ? code : '',
            areaIdList: areaIdList,
          };
          const res = await statisticWorkStatusControllerGetMonthYearWorkStatusPage(params);
          if (res.success) {
            setTotal(res.data.sum);
            changeIsEmpty(res?.data.page.total !== '0');
            return {
              data: res.data.page.records,
              success: res.success,
              total: res?.data.page.total,
            };
          }
        }}
        summary={() =>
          isEmpty && (
            <ProTable.Summary.Row>
              <ProTable.Summary.Cell index={0}>
                {intl.formatMessage({ id: 'statistics.common.monthSum' })}
              </ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={1}></ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={2}>{total.chargeCount}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={3}>{total.dischargeCount}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={4}>{total.standbyCount}</ProTable.Summary.Cell>
              {stationToken && (
                <ProTable.Summary.Cell index={5}>{total.debugCount}</ProTable.Summary.Cell>
              )}
              <ProTable.Summary.Cell index={6}>{total.faultCount}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={7}>{total.chargeTime}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={8}>{total.dischargeTime}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={9}>{total.standbyTime}</ProTable.Summary.Cell>
              {stationToken && (
                <ProTable.Summary.Cell index={10}>{total.debugTime}</ProTable.Summary.Cell>
              )}
              <ProTable.Summary.Cell index={11}>{total.faultTime}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={12}>{total.dischargeEnergy}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={13}>{total.chargeEnergy}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={14}>{total.pocOnGridEnergy}</ProTable.Summary.Cell>
              <ProTable.Summary.Cell index={15}>{total.pocOffGridEnergy}</ProTable.Summary.Cell>
            </ProTable.Summary.Row>
          )
        }
        search={{
          className: 'searchPosInline',
        }}
        toolbar={{
          className: 'toobalrZindex',
          actions: [
            // eslint-disable-next-line react/button-has-type
          ],
        }}
      ></ProTable>
    </>
  );
};

export default MonthReport;
